package com.example.utils;

import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class XmlParserUtils {
    //xml 解析

    public static <T> List<T> parse(String file, Class<T> targetClass) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {

        ArrayList<T> list = new ArrayList<>();

        // 读取 XML 文件
        File xmlFile = new File(file);
        Document document = XmlUtil.readXML(xmlFile);

        //获取元素
        Element rootElement = document.getDocumentElement();
        NodeList nodeList = rootElement.getElementsByTagName("emp");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);

            String name = element.getElementsByTagName("name").item(0).getTextContent();
            String age = element.getElementsByTagName("age").item(0).getTextContent();
            String image = element.getElementsByTagName("image").item(0).getTextContent();
            String gender = element.getElementsByTagName("gender").item(0).getTextContent();
            String job = element.getElementsByTagName("job").item(0).getTextContent();

            //组装数据
            Constructor<T> constructor = targetClass.getDeclaredConstructor(String.class, int.class, String.class, String.class, String.class);
            constructor.setAccessible(true);
            T object = constructor.newInstance(name, Integer.parseInt(age), image, gender, job);

            list.add(object);

        }

        return list;
    }

}
